package com.mindainfo.groundwave.server.device.dao.impl;

import com.mindainfo.groundwave.server.device.bean.DeviceOperate;
import com.mindainfo.groundwave.server.device.dao.IDeviceOperateDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.*;

/**
 * Created by MD-01 on 2017/6/13.
 */
@Repository
public class DeviceOperateDaoImpl implements IDeviceOperateDao {

    @Resource
    private JdbcTemplate template;
    @Override
    public int add(DeviceOperate operate) {

        String sql = "insert into device_operate (operate,door_id,time,state) values(?,?,?,?)";

        KeyHolder keyHolder = new GeneratedKeyHolder();
        template.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {

                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1,operate.getOperate());
                ps.setInt(2,operate.getDoorId());
                ps.setTimestamp(3,new Timestamp(operate.getTime().getTime()));
                ps.setInt(4,operate.getState());
                return ps;
            }
        },keyHolder);
        return keyHolder.getKey().intValue();
    }
}
